<?php
namespace Api\Controller;
use Think\Controller;
use Wx\Model\SendMsgModel;


/**
 * 微信支付
 */
class WeixinpayController extends Controller{

    // 选择支付方式页面
    public function choosePay(){
        $order_id = intval(I('order_id'));
        $order_info = getInfo('shop_spellgroup_order',array('id'=>$order_id,'u_id'=>session('u_id')),'id,addtime,state,total_fee,u_id,order_sn');
        if($order_info['state']==0){
//            dump($order_info);
            $credit2 = M('member')->where('id='.session('u_id'))->getField('credit2');  //卡额
            $u_pass = M('member')->where('id='.session('u_id'))->getField('pay_pwd');  //用户支付密码
            $this->assign('order_info',$order_info);
            $this->assign('credit2',$credit2);
            $this->assign('u_pass',$u_pass);
            $this->display();
        }else{
            $this->error('非法进入');
        }
    }// end fun choosePay()

    // 卡额支付页面
    public function cardPay(){
        if(IS_POST){
            $order_id = $_GET['order_id'];
            $pass = md5(I('password'));
            $u_pass = M('member')->where('id='.session('u_id'))->getField('pay_pwd');  //卡额
            if($pass!=$u_pass){
                $this->error('支付密码错误');
            }
            $order = M('shop_spellgroup_order');
            $order_info = $order->where('id='.$order_id)->find();
            if($order_info){
                // 调用支付成功后的处理
                $this->groupnotify($order_info);
                // 将用户购买的商品id放到session中；
                $sg_id = M('shop_spellgroup_copy')->where('id='.$order_info['c_id'])->getField('sg_id');
                session('sg_id',$sg_id);

                // 余额支付，更新
                $data = $order->where('id='.$order_id)->find();
                $data['card_fee'] = $order_info['total_fee'];
                $data['total_fee'] = 0.00;
                $order->save($data);
                //用户卡额减少
                M('member')->where('id = '.session('u_id'))->setDec('credit2',$order_info['total_fee']);
                //卡额变动记录
                changeCredit($order_info['u_id'],'拼团','credit2','-',$order_info['total_fee']);   //增加积分变动记录
                $this->success('支付成功','/Wx/Prodetail/index/share/1');
            }
        }
    }




    /**
     * 拼团-公众号支付 必须以get形式传递 order_id 参数,即订单id
     */
    public function pay(){
        $order_id = intval(I('order_id'));
        if($order_id){
            // 获取订单信息
            $order_info = getInfo('shop_spellgroup_order',array('id'=>$order_id,'u_id'=>session('u_id'),'state'=>0),'id,total_fee,c_id,u_id,order_sn');
            $order_info['openid'] = M("member")->where("id = {$order_info['u_id']}")->getField('openid');
            // 获取商品id
            $sg_id = M("shop_spellgroup_copy")->where("id = {$order_info['c_id']}")->getField('sg_id');
            // 判断商品是否已经下架
            $sg_status = M("shop_spellgroup")->where('id='.$sg_id)->getField('state');
            if($sg_status!=1){//如果下架,处理商品状态，跳转到售罄页面
                M("shop_spellgroup_order")->where('id='.$order_id)->setField('state',8);
                redirect('/Wx/SoldOut/index');
            }
            // 将用户购买的商品id放到session中；
            session('sg_id',$sg_id);
            $order_info['order_title'] = M("shop_spellgroup")->where("id = {$sg_id}")->getField('title');
            // 导入微信支付sdk
            Vendor('Weixinpay.Weixinpay');
            $wxpay = new \Weixinpay();
            // 获取jssdk需要用到的数据
            $data = $wxpay->getParameters($order_info);
            // 将数据分配到前台页面
            $assign = array(
                'data'=>json_encode($data)
            );
            $this->assign($assign);
            $this->display();
        }// end if
    }// end fun pay()


    /**
     * notify_url接收页面，在这里写业务逻辑
//     */
    public function notify(){
        // 导入微信支付sdk
        Vendor('Weixinpay.Weixinpay');
        $wxpay = new \Weixinpay();
        $result = $wxpay->notify();
        file_put_contents('./notify.text', $result);
        if ($result) {
            $type = substr($result['out_trade_no'], 0, 2);
            if($type=='Ws'){// 如果是心愿团支付，调用心愿团回调方法
                $this->wishnotify($result);
            }else if($type=='Re'){// 如果是充值，调用充值回调方法
                $this->recharge_notify($result);
            }else{//否则为拼团订单支付
                // 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单号
                $order_info = M('shop_spellgroup_order')->where(array('order_sn'=>$result['out_trade_no']))->find();
                $this->groupnotify($order_info);
                echo 'SUCCESS';
            }// end if

        }// end if
    }// end fun notify()

    //  拼团支付-支付成功处理
    public function groupnotify($order_info){
        // 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单号
        $order = M('shop_spellgroup_order');
        //调用拼团推送消息接口
        $model = new SendMsgModel();
        $tourl = 'http://www.xiangtws.com/Wx/MyGrouporder/orderdetail/id/'.$order_info['id'];   //跳转链接
        $first = '您有新的拼团订单已经组团成功';
        $status = '拼团成功';

        //积分变动，向上取整
        $change_credit1 = ceil($order_info['total_fee']);

        // 更新副本商品数量
        $copy = M('shop_spellgroup_copy');
        $copy->where(array('id'=>$order_info['c_id']))->setInc('num',$order_info['num']);

        // 对比副本商品数量与拼团商品最低标准
        $copy_info = $copy->where(array('id'=>$order_info['c_id']))->field('id,sg_id,num')->find();
        // 查询拼团商品类型
        $sg_type = M('shop_spellgroup')->where('id='.$copy_info['sg_id'])->getField('type');
        $title = M('shop_spellgroup')->where('id='.$copy_info['sg_id'])->getField('title');
        $s_url = '<a href="http://www.xiangtws.com/Wx/MyGrouporder/orderdetail/id/'.$order_info['id'].'" style="color: #ff4400">'.$title.'</a>';
        if($copy_info['orsuccess']==1){
            $order_info['state'] = 4;   //乡村-更新订单状态-拼成待发货
            // 拼团成功减库存
            M('shop_spellgroup')->where('id = '.$copy_info['sg_id'])->setDec('num',$order_info['num']);
            //积分增加
            M('member')->where('id = '.$order_info['u_id'])->setInc('credit1',$change_credit1);
            changeCredit($order_info['u_id'],'拼团','credit1','+',$change_credit1);   //增加积分变动记录
            //发送系统消息
            sendVoice($order_info['u_id'],'您的订单'.$s_url.'拼团成功！增加积分'.$change_credit1);
            //推送微信消息
            $model->groupmsg($order_info['u_id'],$first,$status,$title,$order_info['total_fee'],$tourl);
            //增加成长值以及历史成长值
            M('member')->where('id = '.$order_info['u_id'])->setInc('growth',$change_credit1);
            M('member')->where('id = '.$order_info['u_id'])->setInc('growth_history',$change_credit1);
        }else{
            $min_num = M('shop_spellgroup')->where('id='.$copy_info['sg_id'])->getField('min_num');
            if($copy_info['num']>=$min_num){// 则表明拼团成功
                $copy_info['orsuccess'] = 1;    //拼团状态-成功
                // 门店拼团不需要发货-直接进入待通知状态
                if($sg_type==0){//乡村-副本状态-发货
                    $copy_info['state'] = 1;
                }else{//门店-副本状态-成团待通知
                    $copy_info['state'] = 3;
                }
                $copy->save($copy_info);
                // 拼团成功减库存,查询该副本的所拼份数，再减去对应商品的数量
                $sg_num = $copy->where('id='.$order_info['c_id'])->getField('num');
                M('shop_spellgroup')->where('id = '.$copy_info['sg_id'])->setDec('num',$sg_num);
                // 更新该订单状态-拼成待发货
                $order_info['state'] = 4;
                //积分增加
                M('member')->where('id = '.$order_info['u_id'])->setInc('credit1',$change_credit1);
                //增加积分变动记录
                changeCredit($order_info['u_id'],'拼团','credit1','+',$change_credit1);
                // 推送系统消息
                sendVoice($order_info['u_id'],'您的订单'.$s_url.'拼团成功！增加积分'.$change_credit1);
                //推送微信消息
                $model->groupmsg($order_info['u_id'],$first,$status,$title,$order_info['total_fee'],$tourl);
                //增加成长值、历史成长值
                M('member')->where('id = '.$order_info['u_id'])->setInc('growth',$change_credit1);
                M('member')->where('id = '.$order_info['u_id'])->setInc('growth_history',$change_credit1);
                // 副本下所有用户改变订单状态、增加积分、推送系统消息
                $order_list = $order->where(array('c_id'=>$order_info['c_id'],'state'=>1))->select();
                if($order_list!=''){
                    foreach ($order_list as $v){
                        // 更新该副本下所有已付款订单的状态-拼成待发货
                        $order->where('id='.$v['id'])->setField('state',4);
                        // 如果是total_fee为0。00，说明是卡额支付
                        if($v['total_fee']==0.00){
                            $v['total_fee'] = $v['card_fee'];
                        }
                        //积分增加
                        M('member')->where('id = '.$v['u_id'])->setInc('credit1',ceil($v['total_fee']));
                        // 增加积分变动记录
                        changeCredit($v['u_id'],'拼团','credit1','+',ceil($v['total_fee']));
                        // 推送系统消息
                        $url = '<a href="http://www.xiangtws.com/Wx/MyGrouporder/orderdetail/id/'.$v['id'].'" style="color: #ff4400">'.$title.'</a>';
                        sendVoice($v['u_id'],'您的订单'.$url.'拼团成功！增加积分'.ceil($v['total_fee']));
                        //推送微信消息
                        $other_tourl = 'http://www.xiangtws.com/Wx/MyGrouporder/orderdetail/id/'.$v['id'];   //跳转链接
                        $model->groupmsg($v['u_id'],$first,$status,$title,$v['total_fee'],$other_tourl);
                        //增加成长值、历史成长值
                        M('member')->where('id = '.$v['u_id'])->setInc('growth',ceil($v['total_fee']));
                        M('member')->where('id = '.$v['u_id'])->setInc('growth_history',ceil($v['total_fee']));
                    }// end foreach
                }// end if

            }else{
                $order_info['state'] = 1;
            }// end if
        }// end if

        // 更新订单状态
        $order_info['paytime'] = time();
        $order->save($order_info);
    }
    

    /**
     * 心愿团支付 必须以get形式传递 order_id 参数,即订单id
     */
    public function wishpay(){
        $order_id = intval(I('order_id'));
        if($order_id){
            // 获取订单信息
            $order_info = getInfo('wish_order',array('id'=>$order_id,'u_id'=>session('u_id'),'pay_status'=>0),'id,total_fee,ws_id,u_id,order_sn');
//            $order_info['total_fee'] = 0.01;
            $order_info['openid'] = M("member")->where("id = {$order_info['u_id']}")->getField('openid');
            // 获取商品名称
            $order_info['order_title'] = '心愿团';
            // 导入微信支付sdk
            Vendor('Weixinpay.Weixinpay');
            $wxpay = new \Weixinpay();
            // 获取jssdk需要用到的数据
            $data = $wxpay->getParameters($order_info);
            // 将数据分配到前台页面
            $assign = array(
                'data'=>json_encode($data)
            );
            $this->assign($assign);
            $this->display();
        }// end if
    }// end fun wishpay()


    /**
     * 心愿团支付-回调地址
     */
    public function wishnotify($result){
        $order = M('wish_order');
        $wish = M('wish_group');
        // 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单号
        $order_info = $order->where(array('order_sn'=>$result['out_trade_no']))->find();
        if($order_info['ws_id']==0){//为0，判断这段时间有没有新的副本生成
            $ws_id =   M('wish_group')->where(array('status'=>0))->getField('id');
            if(!$ws_id){
                $data['addtime'] = time();
                $data['person'] = 1;
                $data['u_id'] = $order_info['u_id'];    //记录开团人id,用于前期调试
                $order_info['ws_id'] = $wish->add($data);
            }else{
                $order_info['ws_id'] = $ws_id;
            }
        }else{//否则，查询心愿团副本信息
            // 成团人数+1
            $person = $wish->where(array('id'=>$order_info['ws_id']))->getField('person');
            if($person==5){//判断之前的副本有没有成团，如果成团，生成新的副本
                $data['addtime'] = time();
                $data['person'] = 1;
                $data['u_id'] = $order_info['u_id'];    //记录开团人id,用于前期调试
                $order_info['ws_id'] = $wish->add($data);
            }else{//没有，原先的人数加1
                $wish->where(array('id'=>$order_info['ws_id']))->setInc('person',1);
                $wish_info = $wish->where(array('id'=>$order_info['ws_id']))->find();
                if($wish_info['person']==5){//如果成团人数达到5，则直接成团
                    $member =  M('member');
                    //查询该副本下所有未更新状态的订单
                    $wish->where('id = '.$wish_info['id'])->setField('status',1);   //修改副本成团状态，1成团
                    $group_list = $order->where(array('ws_id'=>$wish_info['id'],'pay_status'=>1,'status'=>0))->select();
                    foreach ($group_list as $v){
                        $member->where(array('id'=>$v['u_id']))->setInc('credit1',18); //积分
                        $member->where(array('id'=>$v['u_id']))->setInc('credit2',18); //卡额
                        //增加积分变动记录
                        changeCredit($v['u_id'],'购买心愿卡','credit1','+',18);
                        //增加余额变动记录
                        changeCredit($v['u_id'],'购买心愿卡','credit2','+',18);
                        //修改心愿团状态
                        $order->where(array('id'=>$v['id']))->setField('status',1);
                    }

                    // 用户增加余额和积分
                    $order_info['status'] = 1;  //更新该订单成团状态
                    $member->where(array('id'=>$order_info['u_id']))->setInc('credit1',18); //积分
                    $member->where(array('id'=>$order_info['u_id']))->setInc('credit2',18); //卡额
                    //增加积分变动记录
                    changeCredit($order_info['u_id'],'购买心愿卡','credit1','+',18);
                    //增加余额变动记录
                    changeCredit($order_info['u_id'],'购买心愿卡','credit2','+',18);
                }//end if
            }
        }// 心愿团副本
        $order_info['pay_status'] = 1;  //更新付款状态
        $order_info['paytime'] = time();  //更新付款时间
        $order->save($order_info);
    }// end fun wishnotify()


    /**
     * 充值 必须以get形式传递 order_id 参数,即订单id
     */
    public function recharge(){
        $order_id = intval(I('order_id'));
        if($order_id){
            // 获取订单信息
            $order_info = getInfo('recharge_log',array('id'=>$order_id,'u_id'=>session('u_id'),'pay_status'=>0),'id,total_fee,u_id,order_sn');
            $order_info['openid'] = M("member")->where("id = {$order_info['u_id']}")->getField('openid');
            // 获取商品名称
            $order_info['order_title'] = '充值';
            // 导入微信支付sdk
            Vendor('Weixinpay.Weixinpay');
            $wxpay = new \Weixinpay();
            // 获取jssdk需要用到的数据
            $data = $wxpay->getParameters($order_info);
            // 将数据分配到前台页面
            $assign = array(
                'data'=>json_encode($data)
            );
            $this->assign($assign);
            $this->display();
        }// end if
    }

    /**
     * 充值支付-回调地址
     */
    public function recharge_notify($result){
        // 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单号
        $order_info = M('recharge_log')->where(array('order_sn'=>$result['out_trade_no']))->find();
        $order_info['status'] = 1;          //更新付款状态
        $order_info['paytime'] = time();    //更新付款时间
        M('recharge_log')->save($order_info);
        // 用户增加余额和积分
        $member =  M('member');
        $member->where(array('id'=>$order_info['u_id']))->setInc('credit1',ceil($order_info['total_fee'])); //积分
        $member->where(array('id'=>$order_info['u_id']))->setInc('credit2',$order_info['total_fee']);       //卡额
        //增加余额和积分变动记录
        $credit_log = M('member_credit_log');
        $credit1['u_id'] = $order_info['u_id'];
        $credit1['reason'] = '充值';           //变动原因
        $credit1['credit_type'] = 'credit1';  //变动类型
        $credit1['change_type'] = '+';        //加减类型
        $credit1['change_number'] = ceil($order_info['total_fee']); //变动金额
        $credit1['changetime'] = time();      //变动时间
        $credit_log->add($credit1);

        $credit2 = $credit1;
        $credit2['change_number'] = $order_info['total_fee'];   //变动金额
        $credit2['credit_type'] = 'credit2';
        $credit_log->add($credit2);
    }// end fun recharge_notify()


}